<template>
  <page-view class="login">
    <page-header title="登录" :show-back="true"></page-header>
    <div class="content-box">
      <Form @submit="onSubmit">
        <cell-group inset>
          <!-- 通过 pattern 进行正则校验 -->
          <field
            v-model="zh"
            name="用户名"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <!-- 通过validator 进行函数校验 -->
          <field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ validator: validatorPassword }]"
          />
        </cell-group>
        <!-- 提交前有一个滑块解锁组件 -->
        <Drag @unlock="unlock"></Drag>
        <div style="margin: 16px">
          <Button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="正在登录"
            :disabled="loading"
          >
            提交
          </Button>
        </div>
      </Form>
      <div class="tips">
        还没有账号？去
        <router-link :to="{ name: 'Register' }">注册</router-link>
      </div>
    </div>
  </page-view>
</template>

<script>
import { Form, Field, CellGroup, Button, Toast } from "vant";
import { reactive, getCurrentInstance, ref, toRefs } from "vue";
import { useRouter, useRoute } from "vue-router";
import Api from "../utils/api";
import { useStore } from "vuex";
import Drag from "../components/Drag.vue";

export default {
  name: "Login",
  components: { Form, Field, CellGroup, Button, Toast, Drag },
  setup() {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();

    let userInfo = reactive({
      zh: "",
      password: "",
    });
    let loading = ref(false);

    //滑块解锁
    let clock = false;
    //子给父组件传值 ：父组件定义方法 并传给子组件去调用，子调用后就可以操作父组件中的数据了，达到传值效果
    function unlock() {
      clock = true;
    }

    //校验密码 函数校验中（密码不能为空，长度要在6-18）
    //这个函数校验可以获取绑定的值  用val形参表示
    const validatorPassword = (val) => {
      if (val.trim() === "") {
        return "密码不能为空";
      } else if (val.length < 6 || val.length > 18) {
        return "密码长度不对";
      }
    };

    //表单提交:当点击提交按钮后 先要看滑块是否解锁 把滑块看成一个开关
    const onSubmit = () => {
      console.log("滑块是否解锁？", clock);
      //做滑动没有解锁的处理：
      if (clock == false) {
        Toast.clear(true);
        Toast.fail("请先滑动解锁");
        return;
      }
      checkLogin();
    };

    const checkLogin = async () => {
      Toast.loading({
        message: "登录中",
        forbidClick: true,
        //展示时长(ms)，值为 0 时，toast 不会消失
        duration: 0,
      });
      //让按钮处于加载且禁用的状态
      loading.value = true;
      //发请求看用户是否能够登录
      setTimeout(async () => {
        try {
          let results = await Api.userInfo.checkLogin(userInfo);
          console.log("登录成功后的结果", results);
          Toast.clear(true);
          Toast.success("登录成功");
          store.commit("setUserInfo", results.loginUserInfo);
          store.commit("setToken", results.token);
          store.commit("login")
          // ?????
          
          //登录成功后要跳转到最开始的目标路由：比如未登录时 在foodDetail中点购物车
          console.log(
            "在这个路由中记录了，我一开始想去的路由地址：redirect",
            route
          );
          if (route.query.redirect) {
            router.replace(route.query.redirect);
          } else {
            router.back();
          }
        } catch (error) {
          Toast.fail("登录失败");
        } finally {
          loading.value = false;
        }
      }, 2000);
    };

    return {
      loading,
      ...toRefs(userInfo),
      validatorPassword,
      onSubmit,
      unlock,
      checkLogin,
    };
  },
};
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  flex-direction: column;
  .content-box {
    flex: 1;
    overflow: auto;
    .tips {
      display: flex;
      justify-content: center;
      align-items: center;
      color: gray;
      a {
        color: $primaryColor;
      }
    }
  }
}
</style>